package wdt_qf.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qimencloud.api.DefaultQimenCloudClient;
import com.qimencloud.api.scenehu3cgwt0tc.request.WdtStockinOrderQueryRefundRequest;
import com.qimencloud.api.scenehu3cgwt0tc.request.WdtStockoutOrderQueryTradeRequest;
import com.qimencloud.api.scenehu3cgwt0tc.response.WdtOtherOutStockQueryTradeResponse;
import com.qimencloud.api.scenehu3cgwt0tc.response.WdtStockPdQueryTradeResponse;
import com.qimencloud.api.scenehu3cgwt0tc.response.WdtStockinOrderQueryRefundResponse;
import com.qimencloud.api.scenehu3cgwt0tc.response.WdtStockoutOrderQueryTradeResponse;
import com.taobao.api.ApiException;
import com.wangdian.api.WdtClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import wdt_qf.dao.BuyBillDao;
import wdt_qf.dao.ZxySaleDetailsListDao;
import wdt_qf.dao.ZxySaleIndexDao;
import wdt_qf.dao.ZxySalePositionListDao;
import wdt_qf.entity.ZxySaleDetailsList;
import wdt_qf.entity.ZxySaleIndex;
import wdt_qf.entity.ZxySalePositionList;
import wdt_qf.entity.request.WdtOtherOutStockOrderQueryTradeRequest;
import wdt_qf.entity.request.WdtPdQueryTradeRequest;
import wdt_qf.entity.wdt.*;
import wdt_qf.service.QfBillService;
import wdt_qf.service.QfRetailsBillService;
import wdt_qf.service.WdtService;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j(topic = "WdtServiceImpl")
public class WdtServiceImpl implements WdtService {

    private String serverUrl = "https://hu3cgwt0tc.api.taobao.com/router/qm";
    private String appKey = "33504244";
    private String appSecret = "139efe9f7a2d23569937502b3eb5837f";
    private String format = "json";
    @Resource
    private ZxySaleIndexDao zxySaleIndexDao;
    @Resource
    private ZxySalePositionListDao zxySalePositionListDao;
    @Resource
    private ZxySaleDetailsListDao zxySaleDetailsListDao;
    @Resource
    private QfRetailsBillService qfRetailsBillService;

    @Override
    public WdtHttpResult<WdtSaleBillRes> getWdtSaleBill(WdtSaleQueryInfo queryInfo) {
        WdtHttpResult<WdtSaleBillRes> wdtHttpResult = new WdtHttpResult();
        DefaultQimenCloudClient client = new DefaultQimenCloudClient(serverUrl, appKey, appSecret, format);
        WdtStockoutOrderQueryTradeRequest req = new WdtStockoutOrderQueryTradeRequest();
        req.setTargetAppKey("21363512");//旺店通的奇门appkey
        req.setSid("dek2");//旺店通erp的卖家账号
        req.setStartTime(queryInfo.getStart_time());
        req.setEndTime(queryInfo.getEnd_time());
        req.setPageSize(queryInfo.getPage_size());
        req.setPageNo(queryInfo.getPage_no());
        req.setStatus(queryInfo.getStatus());
        req.setWarehouseNo("XLTX");
//        req.setStatus(queryInfo.getStatus());
        if (!queryInfo.equals("")) {
            req.setSrcOrderNo(queryInfo.getSetSrcOrderNo());
        }
        try {
            WdtStockoutOrderQueryTradeResponse res = client.execute(req);
            System.out.println("code:" + res.getCode());
            if (res.getCode().equals("")) {
                System.out.println("body:" + res.getBody());
                wdtHttpResult = JSONObject.parseObject(res.getBody().toString(), WdtHttpResult.class);
                WdtSaleBillRes wdtSaleBillRes = JSONObject.parseObject(JSON.toJSONString(wdtHttpResult), WdtSaleBillRes.class);
                qfRetailsBillService.addRetailsBillToQianFang(wdtSaleBillRes);
                for (Object o : wdtHttpResult.getResponse().getStockoutList()) {
                    WdtSaleBillRes.ResponseBean.StockoutListBean wdtStockOutListIndex = JSON.parseObject(JSON.toJSONString(o), WdtSaleBillRes.ResponseBean.StockoutListBean.class);
                    ZxySaleIndex zxySaleIndex = JSON.parseObject(JSON.toJSONString(o), ZxySaleIndex.class);
                    ZxySaleIndex zxySaleIndexByOrderNo = zxySaleIndexDao.getZxySaleIndexByOrderNo(zxySaleIndex.getSrc_order_no());
                    if (BeanUtil.isNotEmpty(zxySaleIndexByOrderNo)) {
                        log.error("单据》" + zxySaleIndexByOrderNo.getSrc_order_no() + "已经存在.不需要再次进行插入");
                        break;
                    }
                    zxySaleIndexDao.insertSelective(zxySaleIndex);
                    for (WdtSaleBillRes.ResponseBean.StockoutListBean.DetailsListBean detailsListBean : wdtStockOutListIndex.getDetailsList()) {
                        ZxySaleDetailsList zxySaleDetailsList = new ZxySaleDetailsList();
                        BeanUtil.copyProperties(detailsListBean, zxySaleDetailsList);
                        zxySaleDetailsList.setStockout_id(detailsListBean.getStockoutId());
                        zxySaleDetailsList.setSpec_no(detailsListBean.getSpecNo());
                        zxySaleDetailsList.setGoods_count(detailsListBean.getGoodsCount());
                        zxySaleDetailsList.setSell_price(detailsListBean.getSellPrice());
                        zxySaleDetailsListDao.insertSelective(zxySaleDetailsList);
                        for (WdtSaleBillRes.ResponseBean.StockoutListBean.DetailsListBean.PositionListBean positionListBean : detailsListBean.getPositionList()) {
                            ZxySalePositionList zxySalePosition = new ZxySalePositionList();
                            BeanUtil.copyProperties(positionListBean, zxySalePosition);
                            zxySalePositionListDao.insertSelective(zxySalePosition);
                        }
                    }

                }
            } else {
                log.error(res.getMessage());
            }
        } catch (ApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return wdtHttpResult;
    }

    @Override
    public WdtHttpResult<WdtSaleBillRes> getWdtSaleBill2(WdtSaleQueryInfo queryInfo) {
        WdtHttpResult<WdtSaleBillRes> wdtHttpResult = new WdtHttpResult();
        DefaultQimenCloudClient client = new DefaultQimenCloudClient(serverUrl, appKey, appSecret, format);
        WdtStockoutOrderQueryTradeRequest req = new WdtStockoutOrderQueryTradeRequest();
        req.setTargetAppKey("21363512");//旺店通的奇门appkey
        req.setSid("dek2");//旺店通erp的卖家账号
        req.setStartTime(queryInfo.getStart_time());
        req.setEndTime(queryInfo.getEnd_time());
        req.setPageSize(queryInfo.getPage_size());
        req.setPageNo(queryInfo.getPage_no());
        req.setStatus(queryInfo.getStatus());
        req.setWarehouseNo("SH");
//        req.setStatus(queryInfo.getStatus());
        if (!queryInfo.equals("")) {
            req.setSrcOrderNo(queryInfo.getSetSrcOrderNo());
        }
        try {
            WdtStockoutOrderQueryTradeResponse res = client.execute(req);
            System.out.println("code:" + res.getCode());
            if (res.getCode().equals("")) {
                System.out.println("body:" + res.getBody());
                wdtHttpResult = JSONObject.parseObject(res.getBody().toString(), WdtHttpResult.class);
                WdtSaleBillRes wdtSaleBillRes = JSONObject.parseObject(JSON.toJSONString(wdtHttpResult), WdtSaleBillRes.class);
                qfRetailsBillService.addRetailsBillToQianFang2(wdtSaleBillRes);
                for (Object o : wdtHttpResult.getResponse().getStockoutList()) {
                    WdtSaleBillRes.ResponseBean.StockoutListBean wdtStockOutListIndex = JSON.parseObject(JSON.toJSONString(o), WdtSaleBillRes.ResponseBean.StockoutListBean.class);
                    ZxySaleIndex zxySaleIndex = JSON.parseObject(JSON.toJSONString(o), ZxySaleIndex.class);
                    ZxySaleIndex zxySaleIndexByOrderNo = zxySaleIndexDao.getZxySaleIndexByOrderNo(zxySaleIndex.getSrc_order_no());
                    if (BeanUtil.isNotEmpty(zxySaleIndexByOrderNo)) {
                        log.error("单据》" + zxySaleIndexByOrderNo.getSrc_order_no() + "已经存在.不需要再次进行插入");
                        break;
                    }
                    zxySaleIndexDao.insertSelective(zxySaleIndex);
                    for (WdtSaleBillRes.ResponseBean.StockoutListBean.DetailsListBean detailsListBean : wdtStockOutListIndex.getDetailsList()) {
                        ZxySaleDetailsList zxySaleDetailsList = new ZxySaleDetailsList();
                        BeanUtil.copyProperties(detailsListBean, zxySaleDetailsList);
                        zxySaleDetailsList.setStockout_id(detailsListBean.getStockoutId());
                        zxySaleDetailsList.setSpec_no(detailsListBean.getSpecNo());
                        zxySaleDetailsList.setGoods_count(detailsListBean.getGoodsCount());
                        zxySaleDetailsList.setSell_price(detailsListBean.getSellPrice());
                        zxySaleDetailsListDao.insertSelective(zxySaleDetailsList);
                        for (WdtSaleBillRes.ResponseBean.StockoutListBean.DetailsListBean.PositionListBean positionListBean : detailsListBean.getPositionList()) {
                            ZxySalePositionList zxySalePosition = new ZxySalePositionList();
                            BeanUtil.copyProperties(positionListBean, zxySalePosition);
                            zxySalePositionListDao.insertSelective(zxySalePosition);
                        }
                    }

                }
            } else {
                log.error(res.getMessage());
            }
        } catch (ApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return wdtHttpResult;
    }


    @Override
    public WdtHttpResult<WdtSaleBillRes> getWdtSaleBackBill(WdtSaleQueryInfo queryInfo) {
        DefaultQimenCloudClient client = new DefaultQimenCloudClient(serverUrl, appKey, appSecret, format);
        WdtStockinOrderQueryRefundRequest req = new WdtStockinOrderQueryRefundRequest();
        req.setTargetAppKey("21363512");//旺店通的奇门appkey
        req.setSid("dek2");//旺店通erp的卖家账号
        req.setStartTime(queryInfo.getStart_time());
        req.setEndTime(queryInfo.getEnd_time());
        req.setPageSize(queryInfo.getPage_size());
        req.setPageNo(queryInfo.getPage_no());
        req.setStatus(queryInfo.getStatus());
        req.setStockinNo(queryInfo.getSetSrcOrderNo());
        try {
            WdtStockinOrderQueryRefundResponse res = client.execute(req);
            System.out.println("code:" + res.getCode());
            System.out.println("message:" + res.getMessage());
            System.out.println("body:" + res.getBody());
            WdtSaleBackBillRes wdtSaleBackBillRes = JSONObject.parseObject(res.getBody(), WdtSaleBackBillRes.class);
            qfRetailsBillService.addRetailsBackBillToQianFang(wdtSaleBackBillRes.getResponse().getStockin_list());
            for (WdtSaleBackBillRes.ResponseBean.StockinListBean stockinListBean : wdtSaleBackBillRes.getResponse().getStockin_list()) {
                log.info(stockinListBean.getWarehouse_no());
                if (stockinListBean.getWarehouse_no().equals("XLTX")) {
                    log.info(JSON.toJSONString(stockinListBean.getDetails_list()));
                }
            }
        } catch (ApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Resource
    private BuyBillDao buyBillDao;

    @Override
    public WdtResponseJson uploadBuyToWdt(String billCode) {
        WdtResponseJson wdtResponseJson = new WdtResponseJson();
        WdtClient client = new WdtClient(IWdtBase.sid, IWdtBase.appKey, IWdtBase.appSecret, IWdtBase.serverUrl);
        WdtBuyBillIndex wdtBillIndex = buyBillDao.getWdtBillIndex(billCode);
        if (BeanUtil.isEmpty(wdtBillIndex)) {
            wdtResponseJson.setCode(-999);
            wdtResponseJson.setMessage(billCode + "单据编号千方不存在!");
            return wdtResponseJson;
        }
        List<WdtBuyBillDetails> wdtBillDetails = buyBillDao.getWdtBillDetails(billCode);
        wdtBillIndex.getDetails_list().addAll(wdtBillDetails);
        String purchase_info_json = JSON.toJSONString(wdtBillIndex);
        Map<String, String> params = new HashMap<String, String>();
        params.put("purchase_info", purchase_info_json);
        log.info(JSON.toJSONString(params));
        try {
            String response = client.execute("stockin_purchase_push.php", params);
            System.out.println(response);
            wdtResponseJson = JSON.parseObject(response, WdtResponseJson.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wdtResponseJson;
    }

    @Override
    public WdtResponseJson uploadOrderBuyToWdt(String billCode) {
        WdtResponseJson wdtResponseJson = new WdtResponseJson();
        WdtClient client = new WdtClient(IWdtBase.sid, IWdtBase.appKey, IWdtBase.appSecret, IWdtBase.serverUrl);
        WdtOrderBuyBillIndex wdtBillIndex = buyBillDao.getWdtOrderBillIndex(billCode);
        if (BeanUtil.isEmpty(wdtBillIndex)) {
            wdtResponseJson.setCode(-999);
            wdtResponseJson.setMessage(billCode + "单据编号千方不存在!");
            return wdtResponseJson;
        }
        List<WdtOrderBuyBillDetails> wdtBillDetails = buyBillDao.getWdtOrderBillDetails(billCode);
        wdtBillIndex.getDetails_list().addAll(wdtBillDetails);
        String purchase_info_json = JSON.toJSONString(wdtBillIndex);
        Map<String, String> params = new HashMap<String, String>();
        params.put("purchase_info", purchase_info_json);
        log.info(JSON.toJSONString(params));
        try {
            String response = client.execute("purchase_order_push.php", params);
            wdtResponseJson = JSON.parseObject(response, WdtResponseJson.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wdtResponseJson;
    }

    @Override
    public WdtResponseJson uploadCGTHToWdt(String billCode) {
        WdtResponseJson wdtResponseJson = new WdtResponseJson();
        WdtClient client = new WdtClient(IWdtBase.sid, IWdtBase.appKey, IWdtBase.appSecret, IWdtBase.serverUrl);
        WdtBuyBackBillIndex wdtBuyBackBillIndex = buyBillDao.getWdtBuyBackBillIndex(billCode);
        if (BeanUtil.isEmpty(wdtBuyBackBillIndex)) {
            wdtResponseJson.setCode(-999);
            wdtResponseJson.setMessage(billCode + "单据编号千方不存在!");
            return wdtResponseJson;
        }
        List<WdtBuyBackBillDetails> wdtBuyBackBillDetails = buyBillDao.getWdtBuyBackBillDetails(billCode);
        wdtBuyBackBillIndex.getDetail_list().addAll(wdtBuyBackBillDetails);
        String purchase_info_json = JSON.toJSONString(wdtBuyBackBillIndex);
        Map<String, String> params = new HashMap<String, String>();
        params.put("return_info", purchase_info_json);
        log.info(JSON.toJSONString(params));
        try {
            String response = client.execute("purchase_return_push.php", params);
            JSONObject jsonObject = JSONObject.parseObject(response);
            Integer code = jsonObject.getInteger("code");
            if (code == 0) {
                wdtResponseJson = uploadCGTHCKToWdt(billCode, jsonObject.getString("message"));
            } else {
                log.error("上传旺店通采购退货单失败" + JSON.toJSONString(response));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return wdtResponseJson;
    }

    @Override
    public WdtResponseJson uploadCGTHCKToWdt(String billCode, String WdtBillCode) {
        WdtResponseJson wdtResponseJson = new WdtResponseJson();
        WdtClient client = new WdtClient(IWdtBase.sid, IWdtBase.appKey, IWdtBase.appSecret, IWdtBase.serverUrl);
        WdtBuyBackOutStockBillIndex wdtBuyBackOutStockBillIndex = buyBillDao.getWdtBuyBackOutStockBillIndex(billCode);
        if (BeanUtil.isEmpty(wdtBuyBackOutStockBillIndex)) {
            wdtResponseJson.setCode(-999);
            wdtResponseJson.setMessage(billCode + "单据编号千方不存在!");
            return wdtResponseJson;
        }
        wdtBuyBackOutStockBillIndex.setReturn_no(WdtBillCode);
        List<WdtBuyBackOutStockBillDetails> wdtBuyBackOutStockBillDetails = buyBillDao.getWdtBuyBackOutStockBillDetails(billCode);
        wdtBuyBackOutStockBillIndex.getDetail_list().addAll(wdtBuyBackOutStockBillDetails);
        String purchase_info_json = JSON.toJSONString(wdtBuyBackOutStockBillIndex);
        Map<String, String> params = new HashMap<String, String>();
        params.put("purchase_return_info", purchase_info_json);
        log.info(JSON.toJSONString(params));
        try {
            String response = client.execute("purchase_return_order_push.php", params);
            System.out.println(response);
            wdtResponseJson = JSON.parseObject(response, WdtResponseJson.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wdtResponseJson;
    }

    @Resource
    private QfBillService qfBillService;

    @Override
    public WdtHttpResult getWdtOtherOutStockBill(WdtOtherOutStockQueryInfo queryInfo) {
        WdtHttpResult<WdtSaleBillRes> wdtHttpResult = new WdtHttpResult();
        DefaultQimenCloudClient client = new DefaultQimenCloudClient(serverUrl, appKey, appSecret, format);
        WdtOtherOutStockOrderQueryTradeRequest req = new WdtOtherOutStockOrderQueryTradeRequest();
        req.setTargetAppKey("21363512");//旺店通的奇门appkey
        req.setSid("dek2");//旺店通erp的卖家账号
        req.setStartTime(queryInfo.getStart_time());
        req.setEndTime(queryInfo.getEnd_time());
        req.setPageSize(queryInfo.getPage_size());
        req.setPageNo(queryInfo.getPage_no());
        req.setStatus(queryInfo.getStatus());
        req.setWarehouseNo(queryInfo.getWarehouseNo());
        if (!queryInfo.equals("")) {
            req.setSrcOrderNo(queryInfo.getSetSrcOrderNo());
        }
        try {
            WdtOtherOutStockQueryTradeResponse res = client.execute(req);
            log.info("拉取到的旺店通其他出库单数据为" + JSON.toJSONString(res));
            log.info("拉取到的旺店通其他出库单数据为" + JSON.toJSONString(res.getStockoutList()));
            System.out.println("code:" + res.getCode());
            qfBillService.aaddOtherBillToQf(res);
            if (res.getCode().equals("")) {
                //调用生成其他出库单接口
            } else {
                log.error(res.getMessage());
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return wdtHttpResult;
    }

    @Override
    public WdtHttpResult getWdtPDBill(WdtPdBillQueryInfo queryInfo) {
        WdtHttpResult<WdtSaleBillRes> wdtHttpResult = new WdtHttpResult();
        DefaultQimenCloudClient client = new DefaultQimenCloudClient(serverUrl, appKey, appSecret, format);
        WdtPdQueryTradeRequest req = new WdtPdQueryTradeRequest();
        req.setTargetAppKey("21363512");//旺店通的奇门appkey
        req.setSid("dek2");//旺店通erp的卖家账号
        req.setStartTime(queryInfo.getStart_time());
        req.setEndTime(queryInfo.getEnd_time());
        req.setPageSize(queryInfo.getPage_size());
        req.setPageNo(queryInfo.getPage_no());
        req.setWarehouseNo(queryInfo.getWarehouse_no());
        try {
            WdtStockPdQueryTradeResponse res = client.execute(req);
            log.info("拉取到的旺店通盘点单数据为" + JSON.toJSONString(res));
            System.out.println("code:" + res.getCode());
            qfBillService.addStockZdPdToQf(res);
            if (res.getCode().equals("")) {
                //调用生成其他出库单接口
            } else {
                log.error(res.getMessage());
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return wdtHttpResult;
    }
}
